import { useEffect, useMemo } from 'react';
import { useTableContext } from '../context';
import { calculateErrorStats } from '../utils/errorUtils';
import { actions } from '../reducer/actions';
import { TColumn } from '@/components/editable-excel-table';

export function useErrorStats({}) {
    const { state, dispatch } = useTableContext();
    const data = state.sheetData.data;
    const columns = state.sheetData.columns as TColumn[];

    // 计算错误统计并更新全局错误位置信息与计数
    useEffect(() => {
        const errorStats = calculateErrorStats(data, columns, state.initialData, state.modifiedCells);
        dispatch(actions.setErrorPositions(errorStats.remainingErrorPositions));
        dispatch(actions.setErrorCount(errorStats.totalErrors, errorStats.fixedErrorCount));
    }, [data, columns, state.initialData, state.modifiedCells, dispatch]);

    // 计算一次错误统计用于渲染时复用，避免在 map 中重复计算
    const errorStats = useMemo(() => {
        return calculateErrorStats(data, columns, state.initialData, state.modifiedCells);
    }, [data, columns, state.initialData, state.modifiedCells]);

    return { errorStats, data, columns } as const;
}
